package demo.xiaxl.com.android_demo.pagersnaphelper;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import demo.xiaxl.com.android_demo.R;

public class TitleAdapter extends BaseAdapter {

    public List<String> titles = new ArrayList<>();
    ListView listView;

    public TitleAdapter(ArrayList<String> datas, ListView lv) {
        titles.addAll(datas);
        listView = lv;
    }

    @Override
    public int getCount() {
        return titles.size();
    }

    @Override
    public Object getItem(int position) {
        return titles.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_title, null);
            viewHolder = new ViewHolder();
            viewHolder.tvTitle = convertView.findViewById(R.id.tvTitle);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.tvTitle.setText(titles.get(position));
        ListView.LayoutParams rl = (ListView.LayoutParams) viewHolder.tvTitle.getLayoutParams();
        if (rl == null) {
            rl = new ListView.LayoutParams(listView.getWidth(), dp2px(parent.getContext(),48));
        }
        viewHolder.tvTitle.setLayoutParams(rl);
        return convertView;
    }

    public static class ViewHolder {
        TextView tvTitle;
    }

    public int dp2px(Context context, float dipValue) {

        float m = context.getResources().getDisplayMetrics().density;

        return (int) (dipValue * m + 0.5f);

    }
}
